package com.taiyi.renaissancemall.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Environment;
import android.view.View;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageToFileUtils {

    private static final String IMG_PATH = Environment.getExternalStorageDirectory() + "/accToken/share/";

    public static final String IMG_NAME = "share_img.png";


    public final static Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            int length = conn.getContentLength();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;    // 设置缩放比例
            Rect rect = new Rect(0, 0, 0, 0);
            bitmap = BitmapFactory.decodeStream(bis, rect, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    //保存方法
    public static File saveFile(Bitmap bm) throws IOException {
        File foder = new File(IMG_PATH);
        if (!foder.exists()) {
            foder.mkdirs();
        }

        File myCaptureFile = new File(IMG_PATH, System.currentTimeMillis()+"_"+IMG_NAME);
        String ends = myCaptureFile.getPath();

        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();

        return myCaptureFile;
    }


    /**
     * 截取指定View为图片
     *
     * @param view
     * @return
     * @throws Throwable
     */
    public static Bitmap captureView(View view) throws Throwable {
        Bitmap bm = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        view.draw(new Canvas(bm));
        return bm;
    }


}
